package com.zzy.mccjt.core.interceptor;

import com.zzy.mccjt.exception.UnauthorizedException;
import com.zzy.mccjt.model.CurrentClient;
import com.zzy.mccjt.model.CurrentTenant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.zzy.mccjt.constant.RequestConstant.CLIENT_KEY;

/**
 * @program: mccjt-cloud
 * @description:
 * @author: zhouyang.zheng
 * @create: 2022-08-02 17:42
 **/
@Slf4j
public class OpenApiRequestInterceptor extends AbstractRequestInterceptor {

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        CurrentClient.clear();
        CurrentTenant.clear();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        handleTenantInfo(request, (HandlerMethod) handler);

        if (isNoAuth(request, (HandlerMethod) handler)) {
            return true;
        }

        String clientKey = request.getHeader(CLIENT_KEY);
        if (!StringUtils.isEmpty(clientKey)) {
            CurrentClient.set(clientKey);
            return true;
        }

        throw new UnauthorizedException(HttpStatus.UNAUTHORIZED.value(), "UNAUTHORIZED");
    }
}

